package com.junjiao.util.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie操作类
 * 
 * @author jiaojun
 * @email eshore_jiaojun@163.com
 * @version 2.0
 * @date 2011-1-20
 */
public class CookieUtil {
	/**
	 * 添加cookie
	 * 
	 * @param key
	 *            主键
	 * @param value
	 *            值 默认情况下cookie保存到.118114.cn根目录下，并且存放时间为1周
	 */
	public static void writeCookie(String key, String value,
			HttpServletResponse response) {
		writeCookie(key, value, 60 * 60 * 24 * 7, response);
	}

	/**
	 * 添加cookie
	 * 
	 * @param key
	 *            主键
	 * @param value
	 *            值
	 * @param maxAge
	 *            有效时间
	 * @param response
	 *            响应 默认情况下cookie保存到.118114.cn根目录下
	 */
	public static void writeCookie(String key, String value, int maxAge,
			HttpServletResponse response) {
		writeCookie(key, value, 60 * 60 * 24 * 365, "/", "118114.cn", response);
	}

	/**
	 * 添加cookie
	 * 
	 * @param key
	 *            主键
	 * @param value
	 *            值
	 * @param maxAge
	 *            有效时间
	 * @param path
	 *            路径
	 * @param domain
	 *            域名
	 * @param response
	 *            响应
	 */
	public static void writeCookie(String key, String value, int maxAge,
			String path, String domain, HttpServletResponse response) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(path);
		cookie.setDomain(domain);
		response.addCookie(cookie);
	}

	/**
	 * 获取ookie
	 * 
	 * @param request
	 *            请求
	 * @param key
	 *            主键
	 * @return String 读取key 对应的值
	 */
	public static String readCookie(String key, HttpServletRequest request) {
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				if (c.getName().equalsIgnoreCase(key)) {
					value = c.getValue();
					return value;
				}
			}
		}
		return value;
	}

}